package com.example.libary.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.libary.common.Result;
import com.example.libary.common.ResultCode;
import com.example.libary.dto.BorrowRecordDTO;
import com.example.libary.entity.BorrowRecord;
import com.example.libary.exception.BusinessException;
import com.example.libary.service.BorrowRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 借阅记录控制器
 */
@Tag(name = "借阅管理", description = "借阅记录管理相关接口")
@RestController
@RequestMapping("/borrows")
@RequiredArgsConstructor
public class BorrowRecordController {

    private final BorrowRecordService borrowRecordService;

    /**
     * 借书
     */
    @Operation(summary = "借书", description = "借阅图书")
    @PostMapping("/borrow")
    public Result<Void> borrow(@Parameter(description = "借阅信息") @RequestBody Map<String, Object> borrowInfo) {
        Long userId = Long.valueOf(borrowInfo.get("userId").toString());
        Long bookId = Long.valueOf(borrowInfo.get("bookId").toString());
        Integer days = Integer.valueOf(borrowInfo.get("days").toString());
        
        // 检查图书是否可借
        if (!borrowRecordService.checkBookAvailable(bookId)) {
            throw new BusinessException(ResultCode.BOOK_BORROWED);
        }
        
        boolean success = borrowRecordService.borrow(userId, bookId, days);
        return success ? Result.success() : Result.error("借书失败");
    }

    /**
     * 还书
     */
    @Operation(summary = "还书", description = "归还图书")
    @PostMapping("/return/{id}")
    public Result<Void> returnBook(@Parameter(description = "借阅记录ID") @PathVariable Long id) {
        boolean success = borrowRecordService.returnBook(id);
        return success ? Result.success() : Result.error("还书失败");
    }

    /**
     * 续借
     */
    @Operation(summary = "续借", description = "续借图书")
    @PostMapping("/renew/{id}")
    public Result<Void> renew(
            @Parameter(description = "借阅记录ID") @PathVariable Long id,
            @Parameter(description = "续借天数") @RequestParam Integer days) {
        boolean success = borrowRecordService.renew(id, days);
        return success ? Result.success() : Result.error("续借失败");
    }

    /**
     * 分页查询借阅记录
     */
    @Operation(summary = "分页查询借阅记录", description = "查询借阅记录详情，包含用户姓名和图书名称")
    @GetMapping("/page")
    public Result<Page<BorrowRecordDTO>> page(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer current,
            @Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer size,
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
            @Parameter(description = "图书ID") @RequestParam(required = false) Long bookId,
            @Parameter(description = "状态") @RequestParam(required = false) String status) {
        Page<BorrowRecordDTO> page = new Page<>(current, size);
        Page<BorrowRecordDTO> recordPage = borrowRecordService.pageWithDetails(page, userId, bookId, status);
        return Result.success(recordPage);
    }

    /**
     * 获取借阅记录详情
     */
    @Operation(summary = "获取借阅记录详情", description = "根据ID获取借阅记录详情")
    @GetMapping("/{id}")
    public Result<BorrowRecord> getBorrowRecord(@Parameter(description = "借阅记录ID") @PathVariable Long id) {
        BorrowRecord record = borrowRecordService.getById(id);
        return Result.success(record);
    }

    /**
     * 管理员更新借阅记录
     */
    @Operation(summary = "更新借阅记录", description = "管理员权限")
    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/{id}")
    public Result<Void> updateBorrowRecord(
            @Parameter(description = "借阅记录ID") @PathVariable Long id,
            @Parameter(description = "借阅记录信息") @RequestBody BorrowRecord record) {
        record.setId(id);
        boolean success = borrowRecordService.updateById(record);
        return success ? Result.success() : Result.error("更新失败");
    }
} 